package com.stn.zjx.givingtreasure.fragment.active;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.activity.dynamic.ReleaseDynamicActivity;
import com.stn.zjx.givingtreasure.adapter.DynamicShowItemListAdapter;
import com.stn.zjx.givingtreasure.base.BaseMainFragment;
import com.stn.zjx.givingtreasure.domain.DynamicShowDomain;
import com.stn.zjx.givingtreasure.event.ActiveFragmentEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.RefreshEvent;
import com.stn.zjx.givingtreasure.event.SubmitRefreshEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.UserDynamicNetImpl;
import com.stn.zjx.givingtreasure.service.AmapLocationService;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.widget.MoreLoading;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
@SuppressWarnings("all")
public class DynamicFragment extends BaseMainFragment implements AMapLocationListener {
    public View rootView;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.twinkling_refresh)
    TwinklingRefreshLayout twinklingRefresh;

    Integer pageNow = 1;
    Integer pageSize = 10;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    Unbinder unbinder;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.release_bt)
    RelativeLayout releaseBt;




    private boolean isMoreLoading = false;
    private int visibleItemCount = 0;
    private LinearLayoutManager lm;
    private DynamicShowItemListAdapter adapter;
    public String city = "";
    public String area = "";
    public double longitude = 0;
    public double latitude = 0;
    public String fromAddress = "";

    public AmapLocationService amapLocationService = null;
    private MoreLoading moreLoading;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container) {
        if (rootView == null) {
            rootView = View.inflate(activity, R.layout.fragment_active_dynamic, null);
            ButterKnife.bind(this, rootView);

        }
        return rootView;
    }

    //提交刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSumitDynamic(SubmitRefreshEvent event) {
        if (event.flag == SubmitRefreshEvent.SubmitDynamicRefresh) {
            if (twinklingRefresh != null) {
                twinklingRefresh.startRefresh();
            }
        }
    }

    //退出登录刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFragmentExitRefresh(RefreshEvent event) {
        if (event.flag == RefreshEvent.EXIT_LOGIN_REFRESH) {
            if (twinklingRefresh != null) {
                twinklingRefresh.startRefresh();
            }
        }
    }

    //登录刷新
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFragmentLoginRefresh(RefreshEvent event) {
        if (event.flag == RefreshEvent.LOGIN_REFRESH) {
            if (twinklingRefresh != null) {
                twinklingRefresh.startRefresh();
            }
        }else if(event.flag==RefreshEvent.REFRESH){
            if (twinklingRefresh != null) {
                twinklingRefresh.startRefresh();
            }
        }
    }

    @Override
    public void initData() {
        rv.setLayoutManager(lm = new LinearLayoutManager(activity, OrientationHelper.VERTICAL, false));
        rv.setAdapter(adapter = new DynamicShowItemListAdapter(activity, this));
        ProgressLayout headerView = new ProgressLayout(activity);
        headerView.setColorSchemeResources(R.color.colorAccent);
        twinklingRefresh.setHeaderView(headerView);
        twinklingRefresh.setBottomView(moreLoading = new MoreLoading(activity));


        twinklingRefresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                initStart();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
//                if (!isMoreLoading &&
//                        adapter.dataBeanList.size() >= pageNow * 10) {
                initAppend(city, area, longitude, latitude);
//                }else{
//                    twinklingRefresh.finishLoadmore();
//                }
            }
        });
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!isMoreLoading && newState == RecyclerView.SCROLL_STATE_IDLE && visibleItemCount == adapter.dataBeanList.size() - 1 &&
                        adapter.dataBeanList.size() >= pageNow * 10) {
                    //  initAppend(city, area, longitude, latitude);
                    twinklingRefresh.startLoadMore();
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                visibleItemCount = lm.findLastVisibleItemPosition();

            }
        });

         twinklingRefresh.startRefresh();
//        twinklingRefresh.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                twinklingRefresh.setEnableRefresh(true);
//                initStart();
//            }
//        }, 200);


    }

    public void initStart() {
        ActiveFragmentEvent event = new ActiveFragmentEvent();
        event.flag = ActiveFragmentEvent.ACTIVE_LOCATION_STATUS_CHANGE;
        event.data = getString(R.string.loading_location);
        EventBus.getDefault()
                .post(event);
        amapLocationService = new AmapLocationService(activity);
        amapLocationService.registerListener(this);
        amapLocationService.start();
    }

    public void initRefresh(String city,
                            String area,
                            double longitude,
                            double latitude) {
        String token = "";
        if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
            token = "";
        } else {
            token = UserService.getInstance(activity).getOnlineLoginUser().getToken();
        }
        pageNow = 1;
        UserDynamicNetImpl
                .query_dynamic_location(
                        token,
                        pageNow,
                        pageSize,
                        city,
                        area,
                        longitude,
                        latitude,
                        token + "_initRefresh_query_dynamic_location_" + pageNow, new StringCallback() {
                            @Override
                            public void onFinish() {
                                super.onFinish();

                           twinklingRefresh.finishRefreshing();
                            }

                            @Override
                            public void onCacheSuccess(Response<String> response) {
                                super.onCacheSuccess(response);
                                if (response.isSuccessful() && !activity.isFinishing()) {
                                    DynamicShowDomain domain = new Gson().fromJson(response.body(), DynamicShowDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if (domain.getData() != null && domain.getData().size() != 0) {
                                                noData.setVisibility(View.GONE);
                                                adapter.refreshList(domain.getData());
                                            } else {
                                                adapter.clearList();
                                                noData.setVisibility(View.VISIBLE);
                                            }
                                            break;
                                        default:
                                            adapter.clearList();
                                            noData.setVisibility(View.VISIBLE);
                                            break;
                                    }
                                }
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !activity.isFinishing()) {
                                    DynamicShowDomain domain = new Gson().fromJson(response.body(), DynamicShowDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if (domain.getData() != null && domain.getData().size() != 0) {
                                                noData.setVisibility(View.GONE);
                                                adapter.refreshList(domain.getData());
                                            } else {

                                                adapter.clearList();
                                                noData.setVisibility(View.VISIBLE);
                                            }
                                            break;
                                        default:
                                            adapter.clearList();
                                            noData.setVisibility(View.VISIBLE);
                                            break;
                                    }
                                }

                            }


                        });

    }

    public void initAppend(String city,
                           String area,
                           double longitude,
                           double latitude) {

        String token = "";
        if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
            token = "";
        } else {
            token = UserService.getInstance(activity).getOnlineLoginUser().getToken();
        }
        pageNow++;
        UserDynamicNetImpl
                .query_dynamic_location(
                        token,
                        pageNow,
                        pageSize,
                        city,
                        area,
                        longitude,
                        latitude,
                        "initAppend_query_dynamic_location", new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                isMoreLoading = true;
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                isMoreLoading = false;

                                twinklingRefresh.finishLoadmore();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !activity.isFinishing()) {
                                    DynamicShowDomain domain = new Gson().fromJson(response.body(), DynamicShowDomain.class);
                                    switch (domain.getStatus()) {
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            if (domain.getData() != null && domain.getData().size() != 0) {
                                                adapter.appendList(domain.getData());
                                            }
                                            break;
                                    }
                                }

                            }
                        });

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation.getErrorCode() == 0) {
            city = aMapLocation.getCity();
            area = aMapLocation.getDistrict();
            fromAddress = aMapLocation.getAddress();
            longitude = aMapLocation.getLongitude();
            latitude = aMapLocation.getLatitude();
            initRefresh(city, area, longitude, latitude);
            ActiveFragmentEvent event = new ActiveFragmentEvent();
            event.flag = ActiveFragmentEvent.ACTIVE_LOCATION_STATUS_CHANGE;
            event.data = getString(R.string.success_location);
            EventBus.getDefault()
                    .post(event);
        } else {
            initRefresh(city, area, longitude, latitude);
            ActiveFragmentEvent event = new ActiveFragmentEvent();
            event.flag = ActiveFragmentEvent.ACTIVE_LOCATION_STATUS_CHANGE;
            event.data = getString(R.string.error_location);
            EventBus.getDefault()
                    .post(event);
        }
    }


    @OnClick({R.id.release_bt})
    public void onViewClicked(View view) {
        if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
            RxActivityTool.skipActivity(activity, UserLoginActivity.class);
            return;
        }
        switch (view.getId()) {
            case R.id.release_bt:
                RxActivityTool.skipActivity(activity, ReleaseDynamicActivity.class);
                break;
        }
    }

}
